package com.lancoo.klgcourseware.ui.fragment.basicTrain;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import android.view.View;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.ExpressPracticeModel;
import com.lancoo.klgcourseware.entity.WordPracticeModel;
import com.lancoo.klgcourseware.entity.bean.KlgConstant;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.manager.KlgLocalMediaManager;
import com.lancoo.klgcourseware.manager.KlgMediaManager;
import com.lancoo.klgcourseware.ui.adapter.ViewPagerFragmentAdapter;
import com.lancoo.klgcourseware.ui.fragment.translation.TranslationChildFragment;
import com.stkouyu.entity.LgEvaluateObj;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TranslationTrainFragment extends BasicTrainBaseFragment {

    private static final String EXTRA_REPEAT_TRAIN_MODEL = "repeat_model";

    private TextView mTvQuestionIndex;

    private TextView mTvQuestionCount;

    private ViewPager mViewPagerQuestion;

    private List<ExpressPracticeModel> mModelList;

    private List<TranslationChildFragment> mChildFragments;

    private int mCurrentIndex = 0;

    private KlgMediaManager mRawSourceMediaManager; //原始范音

    private KlgLocalMediaManager mResultMediaManager; //结果提示语

    private boolean mPendingReset = false;

    private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            if (position == mCurrentIndex)
                return;
            stopSpeechEvaluation(false);
            pauseTimer();
            pauseMeidaPlayer();
            pauseDripSoundPlay();

            mChildFragments.get(mCurrentIndex).pauseTrain(
                    mChildFragments.get(mCurrentIndex).getScore()<85
            );

            if (mChildFragments.get(position).getScore()>=85){
                mChildFragments.get(position).processTrain();
            }else  if (!mPendingReset){
                pauseThreeSecondTimer();
                startTrainDialogCountTime(0);
            }

            mPendingReset = false;

//            startTrainDialogCountTime(0);
            mCurrentIndex=position;
            mTvQuestionIndex.setText(getString(R.string.klg_usage_ques_index,mCurrentIndex+1));
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    @SuppressWarnings("unchecked")
    public static TranslationTrainFragment newInstance(List<ExpressPracticeModel> models){
        TranslationTrainFragment repeatTrainFragment = new TranslationTrainFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(EXTRA_REPEAT_TRAIN_MODEL,(ArrayList) models);
        repeatTrainFragment.setArguments(bundle);
        return repeatTrainFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_repeat_train;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseMeidaPlayer();
        stopSpeechEvaluation(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewPagerQuestion.removeOnPageChangeListener(mOnPageChangeListener);

        if(mResultMediaManager!=null){
            mResultMediaManager.release();
        }
        if(mRawSourceMediaManager!=null){
            mRawSourceMediaManager.release();
        }

    }

    private void onTrainStart(){
        recorderProgress=0;
        mChildFragments.get(mCurrentIndex).onTrainStart();
    }

    private void onRawSourceComplete(){
        mChildFragments.get(mCurrentIndex).onRecordProgressUpdate(-1);
    }

    //录音进度更新
    protected void upDateRecordProgress(){
        mChildFragments.get(mCurrentIndex).onRecordProgressUpdate(recorderProgress);
    }

    //测评回调
    protected void onSuccessSpeechEvaluation(int grade, String url, LgEvaluateObj skegnResult){
        mChildFragments.get(mCurrentIndex).onTrainEvaluationSuccess(grade,skegnResult);
        int passCount = 0;
        for (TranslationChildFragment childFragment:mChildFragments){
            if (childFragment.getScore()>= KlgConstant.SCORE_QUALITY){
                passCount++;
            }
        }
        updateTrainResult(passCount*2>=mChildFragments.size());
    }

//    protected void upDateSecondCountTime(){
//
//    }

    protected void updateMediaPlayerProgress(){
        mChildFragments.get(mCurrentIndex).onMediaProgressUpdate(mRawSourceMediaManager.getCurrentPosition());
    }

    //系统倒计时回调
    protected void updateCountTime(int progress,int totalProgress){
        mChildFragments.get(mCurrentIndex).onSystemClockTimer(progress,totalProgress);
    }

    protected void upDateResultCountTime(int progress,int totalProgress){
        mChildFragments.get(mCurrentIndex).onSystemClockTimer(progress,totalProgress);
    }

    //水滴声结束后会调用
    @Override
    protected void startTrain() {
        super.startTrain();
        mChildFragments.get(mCurrentIndex).onDripComplete();
    }

    //播放原音
    protected void playDemonstrationMusic(int musicIndex){

        onTrainStart(); //听音复述，由原声开始播放为训练开始标志

        WordPracticeModel model = mModelList.get(mCurrentIndex).getOneSentenceList().get(0);

        mRawSourceMediaManager.setUpMedia( KlgDbConstant.mediaUrl + model.getSenvoice(), new KlgMediaManager.OnPlayListener() {

            @Override
            public void onComplete() {
//                usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(false);
//                continueTrain();
                pauseMeidaProgressTimer();
                onRawSourceComplete();
            }

            @Override
            public void onStartError() {
//                usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(false);
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
//                usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(false);
            }

            @Override
            public void onResumePlay() {

            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                startMeidaProgressTimer();
                mRawSourceMediaManager.start();


//                usageSubBaseFragmentList.get(currentUsageIndex).imgAninationStateChange(true);
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {

            }
        });

    }

    /**
     * 继续训练
     */
    protected void continueTrain(){
        mChildFragments.get(mCurrentIndex).processTrain();
    }

    /**
     * 重新用法训练，擦除作答记录
     */
    protected void resetUsageTrain(){
//        mChildFragments.get(mCurrentIndex).resetTrain();
        mPendingReset = true;
        for (TranslationChildFragment childFragment:mChildFragments){
            childFragment.resetTrain();
        }
        mViewPagerQuestion.setCurrentItem(0,false);
    }

    protected void pauseCurrentSubTrain(boolean isReset){
        recorderProgress = 0;
        stopSpeechEvaluation(false);
        pauseMeidaPlayer();
        if (isReset){
            for (TranslationChildFragment childFragment:mChildFragments)
                childFragment.resetTrain();
            mViewPagerQuestion.setCurrentItem(0,false);
        }else {
            mChildFragments.get(mCurrentIndex).pauseTrain(false);
        }
//        if(usageSubBaseFragmentList!=null){
//            usageSubBaseFragmentList.get(currentUsageIndex).pauseTrain(isReset);
//            if(isReset){
//                isAutoStudy=false;
//                viewPager.setCurrentItem(0,false);
//            }
//        }
    }

    //播放结果声音
    protected void quesResultMuiscPlayer(boolean isCorrect){
        if(mResultMediaManager==null){
            return;
        }
        try {
            AssetFileDescriptor assetFileDescriptor = getContext().getAssets().openFd(isCorrect?"klg_record_correct.mp3":"klg_record_error.mp3");
            mResultMediaManager.setUpMedia(assetFileDescriptor, new KlgLocalMediaManager.OnPlayListener() {
                @Override
                public void onPrepare() { mResultMediaManager.start();}
                @Override
                public void onComplete() { }
                @Override
                public void onStartError() { }
                @Override
                public void onPausePlay() { }
                @Override
                public void onSourceError() { }
                @Override
                public void onResumePlay() { }
                @Override
                public void onStopPlay() { }
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) { }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //子fragment训练通过
    protected void startNextUsageQuesTrain(){
        if(mCurrentIndex<mChildFragments.size()-1){
            mViewPagerQuestion.setCurrentItem(mCurrentIndex+1,false);
        }else{
            enterNextTrainModel();
//            usageSubBaseFragmentList.get(currentUsageIndex).upDateSecondTimer(secondCountTime);
        }

    }

    private void pauseMeidaPlayer(){
        if(mResultMediaManager!=null){
            mResultMediaManager.pause();
        }
        if(mRawSourceMediaManager!=null){
            mRawSourceMediaManager.pause();
        }
    }

    @Override
    public boolean isPass() {
        for (TranslationChildFragment childFragment : mChildFragments){
            if (childFragment.getScore()<85)
                return false;
        }
        return super.isPass();
    }

    @Override
    protected void initView(View view) {
        currentTrainTag = TRAINTAG_TRANSLATION;
        ViewStub viewStub = view.findViewById(R.id.viewstub_main_data);
        if(viewStub!=null){
            viewStub.inflate();
        }
        mTvQuestionIndex = view.findViewById(R.id.tv_question_index);
        mTvQuestionCount = view.findViewById(R.id.tv_question_count);
        mViewPagerQuestion = view.findViewById(R.id.view_pager);
        changeEnableShowPauseTrainDialogState(true);

        mViewPagerQuestion.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(mViewPagerQuestion!=null){
                    mViewPagerQuestion.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    enableStartTrain(0);
                }
            }
        });
    }

    private void initData(){

        mRawSourceMediaManager=new KlgMediaManager(getContext());
        mResultMediaManager=new KlgLocalMediaManager();

        Bundle bundle = getArguments();
        if (bundle!=null){
            mModelList = bundle.getParcelableArrayList(EXTRA_REPEAT_TRAIN_MODEL);
        }
        if (mModelList == null){
            mModelList = new ArrayList<>();
        }

        mChildFragments = new ArrayList<>();

        for (int i=0;i<mModelList.size();i++){
            mChildFragments.add(TranslationChildFragment.newInstance(mModelList.get(i).getOneSentenceList().get(0),i==mModelList.size()-1));

        }

        ViewPagerFragmentAdapter mAdapter=new ViewPagerFragmentAdapter(getChildFragmentManager(), mChildFragments);
        mViewPagerQuestion.setAdapter(mAdapter);
        mViewPagerQuestion.setOffscreenPageLimit(mChildFragments.size());
        mViewPagerQuestion.addOnPageChangeListener(mOnPageChangeListener);

        mTvQuestionCount.setText(getString(R.string.klg_usage_ques_total,mModelList.size()));
        mTvQuestionIndex.setText(getString(R.string.klg_usage_ques_index,mCurrentIndex+1));
    }

}